package com.gnerv.rabbitmq.agent.handler.factory;

import com.gnerv.rabbitmq.agent.handler.AbstractStatusExecResultHandler;
import com.gnerv.rabbitmq.agent.handler.v_3_7.StatusExecResultHandler;
import com.gnerv.rabbitmq.agent.tools.ExecTools;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;

public class StatusExecResultHandlerFactory extends ExecResultHandlerFactory {

    private static final String CLASS_PATH = "com.gnerv.rabbitmq.agent.handler.%s.StatusExecResultHandler";

    public static AbstractStatusExecResultHandler build(String version, ExecTools.ExecResult execResult) {
        version = convertVersion(version);
        if (StringUtils.hasText(version)) {
            Class<?> clazz = null;
            try {
                String className = String.format(CLASS_PATH, version);
                clazz = Class.forName(className);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("创建处理器出错", e);
            }
            AbstractStatusExecResultHandler statusExecResultHandler = null;
            try {
                statusExecResultHandler = (AbstractStatusExecResultHandler) clazz.getDeclaredConstructor().newInstance();
                statusExecResultHandler.setVersion(version);
                statusExecResultHandler.setExecResult(execResult);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                     NoSuchMethodException e) {
                throw new RuntimeException("创建处理器出错", e);
            }
            return statusExecResultHandler;
        }
        throw new RuntimeException("没有版本信息");
    }


}
